import { AppService } from './../../app/app.serve';
import { Component, ChangeDetectorRef } from '@angular/core';
import { NavController, ModalController, NavParams } from 'ionic-angular';
import { UserCashPage } from './../user-cash/user-cash';
import { UserRechargePage } from './../user-recharge/user-recharge';
import { RulePage } from './../rule/rule';
import { GoodsinfoPage } from './../goodsinfo/goodsinfo';
import { Storage } from '@ionic/storage';
let self;




@Component({
  selector: 'page-tab-home',
  templateUrl: 'tab-home.html'
})
export class TabHomePage {

  page = 1;
  recordPage = 1;
  record_info_box = false;
  interval: any = '';
  interval2: any = '';
  isshowTop = false;
  public countdown = {
    minutes: '00',
    seconds: '00',
    Milliseconds: '00'
  };
  public resData = [];
  public res: any = {};
  public res2: any = {};
  public prev_awardnum;//上期开奖号码
  public userInfo = [];
  public userId = '';
  public goodsList = [];//商品列表
  public newPriseList = [];//开奖揭晓记录
  public hide = false;//控制中间倒计时显示
  public nextOpenTime: number;//剩余的开奖时间 控制首页动画
  public hasBindTel;
  public downTime = 0;
  public milliseconds = 0;
  public runMilliseconds = false;//是否模拟毫秒倒计时
  //页面
  public userCashPage;
  public userRechargePage;
  public rulePage;
  public goodsinfoPage;
  public PageScrollTop = 0;

  constructor(
    public changeDetectorRef: ChangeDetectorRef,
    public navParams: NavParams,
    public storage: Storage,
    public appService: AppService,
    public navCtrl: NavController,
    public modalCtrl: ModalController) {
    self = this;
    this.userCashPage = UserCashPage;
    this.userRechargePage = UserRechargePage;
    this.rulePage = RulePage;
    this.goodsinfoPage = GoodsinfoPage;
    this.storage.get('userInfo').then((val) => {
      console.log('储存在本地的用户信息：', val)
      if (val) {
        this.storage.set('userId', val.id)
        this.userInfo = val;
        this.userId = val.id;
        this.getUserInfo();
      } else {
        this.login();
      }
    })
  }
  ngOnInit() {
    this.getGoodsList();
    this.isWeiXin();
  }
  ionViewWillEnter() {
    this.hide = false;
    clearInterval(self.interval)
    clearInterval(self.interval2)
    this.lottery();
    if (this.userId) {
      this.getUserInfo();
    }
    setTimeout(() => {
      //检测是否绑定了手机号
      this.appService.hasBindTel(true, res => {
        res ? console.log('绑定了手机号') : console.log('未绑定手机号')
      })
    }, 1000);
  }
  showRecordInfoBox() {
    console.log('打开揭晓记录')
    this.getRecord();
    this.record_info_box = true;
  }
  hideRecordInfoBox() {
    console.log('关闭揭晓记录')
    this.record_info_box = false;
  }
  //刷新用户信息
  getUserInfo() {
    this.appService.getUserInfo(this.userId, res => {
      if (res.code == 1) {
        this.userInfo = res.data
      }
    })
  }
  // 商品详情
  goodsinfo(id: number) {
    let state;
    this.hide = true;
    if (this.isshowTop) {
      this.isshowTop = false;
      state = 1;
    };
    this.lottery();
    console.log('当前商品id:', id, '用户id', this.userId)
    const modal = this.modalCtrl.create(this.goodsinfoPage, { id: id, userId: this.userId }, { 'showBackdrop': false });
    modal.onDidDismiss(data => {
      console.log(data);
      this.hide = false;
      if (state == 1) {
        this.isshowTop = true;
      }
      if (data.status == true) {
        this.getUserInfo();
      } else {
        if (data.hasBindTel == false) {
          this.appService.hasBindTel(true);
        }
        console.log('取消操作')
      }
    });
    modal.present();
  }
  CountDown(endTime) {
    clearInterval(this.interval);
    clearInterval(this.interval2);
    setTimeout(() => {
      self.setMilliseconds();
    }, 1500);
    this.interval = setInterval(() => {
      let dat1 = new Date().getTime();
      let dat2 = (endTime - dat1) / 1000
      self.nextOpenTime = dat2;
      if (dat2 >= 0) {
        self.runMilliseconds = true;
        self.countdown.minutes = Math.floor(dat2 / 60);
        if (self.countdown.minutes < 10) {
          self.countdown.minutes = '0' + self.countdown.minutes
        }
        self.countdown.seconds = Math.floor(dat2 % 60);
        if (self.countdown.seconds < 10) {
          self.countdown.seconds = '0' + self.countdown.seconds
        }
      } else {
        console.log('此次计时结束');
        clearInterval(self.interval);
        clearInterval(self.interval2);
        self.runMilliseconds = false;
        self.countdown.Milliseconds = '00';
        setTimeout(() => {
          self.lottery();
        }, 1000);
      }
    }, 1000)
  }
  showTopCountDown(e) {
    let PageScrollTop = document.getElementById('lottery_next').offsetTop + document.getElementById('lx_box').offsetTop;
    if (this.PageScrollTop == 0) {
      this.PageScrollTop = PageScrollTop
    }
    // console.log(e.scrollTop, this.PageScrollTop)
    this.changeDetectorRef.markForCheck();
    if (e.scrollTop >= this.PageScrollTop) {
      this.isshowTop = true
      this.hide = true
    } else {
      this.isshowTop = false
      this.hide = false
    }
    this.changeDetectorRef.detectChanges();
  }
  // 开奖信息
  lottery() {
    this.appService.post('/apiindex/index_lottery_num', { lottery: 'lottery' }, res => {
      console.log('开奖信息:', res)
      this.res = res;
      if (this.res.code == 1) {
        this.resData = this.res.data;
        this.prev_awardnum = this.res.data.prev_awardnum.split(",");
        this.downTime = this.res.data.now_end_time - this.res.data.now_time;
        console.log('倒计时秒数：', this.downTime)
        this.setEndTime(this.downTime)
        console.log(`服务器时间：${this.res.data.now_time},结束时间：${this.res.data.now_end_time},开始时间：${this.res.data.now_start_time},当前期号:${this.res.data.now_issue}`)
        console.log('上期开奖号码：', this.prev_awardnum)
      }
    }, false)
  }

  // 产品列表
  getGoodsList() {
    this.appService.post('/apiindex/index_goods_list', { goods: 'goods', page: this.page }, res => {
      // console.log(res);
      this.goodsList.push(...res.data)
      console.log('产品列表', this.goodsList.length, this.goodsList)
    }, false)
  }
  // 揭晓记录
  getRecord() {
    this.recordPage = 1;
    this.appService.post('/apinewest/newest_prize', { newest: 'newest' }, res => {
      console.log(res)
      if (res.code == 1) {
        res.data.forEach(item => {
          item.awardnum = item.awardnum.split(",");
          item.isOdd = item.num5 % 2 == 0;
        });
        this.newPriseList = res.data;
        console.log('揭晓记录：', this.newPriseList)
      }
    })
  }
  //更多揭晓记录
  getRecordMore() {
    this.recordPage++;
    this.appService.post('/apinewest/newest_prize', { newest: 'newest', page: this.recordPage }, res => {
      console.log(res)
      if (res.code == 1) {
        res.data.forEach(item => {
          item.awardnum = item.awardnum.split(",");
          item.isOdd = item.num5 % 2 == 0;
        });
        this.newPriseList.push(...res.data);
        console.log('揭晓记录：', this.newPriseList)
      }
    })
  }

  // 下拉刷新
  doRefresh(e) {
    console.log('刷新')
    this.goodsList = [];
    this.page = 1;
    this.lottery();
    this.getUserInfo();
    this.getGoodsList();
    setTimeout(() => {
      e.complete();
    }, 1500);
  }
  // 上拉加载更多
  doInfinite(e) {
    console.log('加载更多')
    this.page++;
    this.getGoodsList();
    setTimeout(() => {
      e.complete();
    }, 1500);
  }
  //登陆
  login() {
    let indexUrl = window.location.href;
    // let indexUrl = 'http://second.registerme.cn/?openid=o9ow157JEFdBPrja34H7RuUKA6hE&uid=3&is_tel=0&sign=4dbd374f1ad97c9a70ee63cb72fcf643&user_token=b77d4e6aebaeb3ba2c67fefc2ae07bf5';
    this.appService.post('/apiindex/verify', { 'indexurl': indexUrl }, res => {
      console.log('登录信息：', res)
      if (res.code == 1) {
        this.storage.set('userInfo', res.data)
        this.storage.set('userId', res.data.id)
        this.userId = res.data.id;
        this.userInfo = res.data;
      } else {
        this.appService.alert('获取用户信息失败,请在微信授权后打开')
      }
    }, false)
  }
  isWeiXin() {
    let ua = window.navigator.userAgent.toLowerCase();
    let isWeixin = ua.indexOf('micromessenger') != -1;
    if (isWeixin) {
      console.log('微信环境')
      return true;
    } else {
      console.log('非微信环境')
      return false;
    }
  }
  setMilliseconds() {
    clearInterval(this.interval2)
    this.interval2 = '';
    this.milliseconds = 98;
    this.interval2 = setInterval(() => {
      if (self.runMilliseconds) {
        self.milliseconds -= 11;
        self.countdown.Milliseconds = self.milliseconds;
        if (self.milliseconds < 10) {
          self.countdown.Milliseconds = '0' + self.milliseconds;
        }
        if (self.milliseconds <= 0) {
          self.countdown.Milliseconds = '00';
          self.milliseconds = 98
        }
      } else {
        self.countdown.Milliseconds = '00';
      }

    }, 100)
  }
  // 设置结束时间
  setEndTime(lastTime) {
    let endTime = (new Date()).getTime() + lastTime * 1000
    this.CountDown(endTime)
  }

}
